package com.zsc.spring.study.profile;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.util.StringValueResolver;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

/**
 * Profile:
 * 		spring提供的可以根据当前环境，动态的激活和切换一系列组件的功能
 *1)加了环境标识的bean,只有这个环境被激活的时候才能注册到容器中，默认是defalu环境
 *
 *
 *	1.使用命令行动态参数：在虚拟机参数位置加载-Dspring.profiles.active=dev
 *	2.代码方式激活某种环境
 *
 */
@Profile("test")
@PropertySource("classpath:/db.properties")
@Configuration
public class MainConfigOfProfile implements EmbeddedValueResolverAware {

    @Value("${db.user}")
    private String user;

    private String stringValue;

    @Profile("test")
    @Bean("testDataSource")
    public DataSource dataSourceTest(@Value("${db.pwd}") String pwd) throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(user);
        dataSource.setPassword(pwd);
        dataSource.setDriverClass(stringValue);
        return dataSource;
    }

    @Profile("dev")
    @Bean("devDataSource")
    public DataSource dataSourceDev(@Value("${db.pwd}") String pwd) throws PropertyVetoException{
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(user);
        dataSource.setPassword(pwd);
        dataSource.setDriverClass(stringValue);
        return dataSource;
    }



    public void setEmbeddedValueResolver(StringValueResolver resolver) {
        this.stringValue = resolver.resolveStringValue("${db.driverClass}");
    }
}

